package com.zhou.org.controller;


import com.zhou.framework.aop.anotation.LogOption;
import com.zhou.framework.aop.enums.LogLevel;
import com.zhou.framework.model.PageResult;
import com.zhou.framework.model.RS;
import com.zhou.framework.util.PageUtil;
import com.zhou.org.dao.BlackList;
import com.zhou.org.dto.BlackListSaveDto;
import com.zhou.org.service.BlackListService;
import com.zhou.util.TimeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lang.zhou
 * @since 2022-05-06
 */
@Api(tags = "黑名单接口")
@RestController
@RequestMapping("/sys/blackList")
public class BlackListController {
    @Autowired
    private BlackListService service;

    @ApiOperation("黑名单列表")
    @LogOption(LogLevel.QUERY)
    @PostMapping("/list")
    public Object list(@RequestBody Map<String,Object> map){
        PageResult<BlackList> rs = new PageResult<>(map);
        PageUtil.offsetPage(rs.getPageInfo());
        List<BlackList> list = service.list(map);
        return PageUtil.result(rs,list);
    }

    @ApiOperation("保存黑名单")
    @LogOption(LogLevel.QUERY)
    @PostMapping("/save")
    public Object save(@RequestBody @Validated BlackListSaveDto dto){
        BlackList ip = service.getByIp(dto.getHost());
        if(ip != null && !Objects.equals(ip.getId(),dto.getId())){
            return RS.failed("ip已存在");
        }
        if(ip == null){
            ip = new BlackList();
        }
        ip.setHost(dto.getHost());
        ip.setCreateDt(TimeUtil.parseDate(dto.getCreateDt(),"yyyy-MM-dd HH:mm"));
        ip.setReleaseDt(TimeUtil.parseDate(dto.getReleaseDt(),"yyyy-MM-dd HH:mm"));
        ip.setReason(dto.getReason());
        ip.setStatus(dto.getStatus() ? 1 : 0);
        service.saveBlackItem(ip);
        return RS.success();
    }
}

